import { Button, Col, List, Modal, Row, Spin } from "antd";
import { Card, ListView, Tabs, WhiteSpace } from "antd-mobile";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
// import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import './index.less';
const tabs = [
    { title: '待支付' },
    { title: '待服务' },
    { title: '服务中' },
    { title: '已完成' },
];

const serverArrKey = '$serverArr';
function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}
/**
 * 组件：我的订单表视图控件状态
 */
export interface MyOrderViewState extends ReactViewState {

    /** 长列表数据 */
    dataSource?: any;
    /** 请求的数据 */
    list?: any[];
    /** 上拉加载 */
    upLoading?: boolean;
    /** 下拉刷新 */
    pullLoading?: boolean;
    /** 长列表容器高度 */
    height?: any;
    /** 未服务数据 */
    will_service?: any[];
    /** 服务中的数据 */
    service_ing?: any[];
    /** 服务完成的数据 */
    did_service?: any[];
    open_link_server: boolean;
    server_link_info: any[];
    loading: boolean;
}
/**
 * 组件：我的订单表视图控件
 */
export class MyOrderView extends ReactView<MyOrderViewControl, MyOrderViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            list: [],
            will_service: [],
            service_ing: [],
            did_service: [],
            upLoading: false,
            pullLoading: false,
            height: document.documentElement!.clientHeight,
            open_link_server: false,
            server_link_info: [],
            loading: true
        };
    }
    componentDidMount() {
        AppServiceUtility.my_order_service.my_order_list!({ 'pay_state': '待支付' })!
            .then((data) => {
                console.log(data);
                this.setState({
                    loading: false,
                    list: data.result
                });
            })
            .catch((err) => {
                console.info(err);
            });
        AppServiceUtility.my_order_service.my_order_list!({ 'status': '未服务' })!
            .then((data) => {
                let dataTmp: any[] = [];
                if (data.result!.length > 0) {
                    data.result!.map((e, i) => {
                        if (e['pay_state'] === '待支付') {
                            return;
                        } else {
                            dataTmp.push(e);
                        }
                    });
                }
                this.setState({
                    loading: false,
                    will_service: dataTmp
                });
            })
            .catch((err) => {
                console.info(err);
            });
        AppServiceUtility.my_order_service.my_order_list!({ 'status': '服务中' })!
            .then((data) => {
                // 服务人员去重
                if (data.result!.length > 0) {
                    data.result!.map((e, i) => {
                        let serverId: any[] = [];
                        let serverArr: any[] = [];

                        if (e['servicer_info'].length > 0) {
                            for (let index = 0; index < e['servicer_info'].length; index++) {
                                const element = e['servicer_info'][index];

                                if (serverId.indexOf(element['id']) !== -1) {
                                    continue;
                                } else {
                                    serverArr.push(element);
                                    serverId.push(element['id']);
                                }
                            }
                        }
                        e[serverArrKey] = serverArr;
                    });
                }
                this.setState({
                    loading: false,
                    service_ing: data.result
                });
            })
            .catch((err) => {
                console.info(err);
            });
        AppServiceUtility.my_order_service.my_order_list!({ 'status': '已完成' })!
            .then((data) => {
                this.setState({
                    loading: false,
                    did_service: data.result
                });
            })
            .catch((err) => {
                console.info(err);
            });
    }

    onClickContact = (servers: any[]) => {
        this.setState({
            server_link_info: servers,
            open_link_server: true
        });
    }

    onClickRow = (id: string) => {
        this.props.history!.push(ROUTE_PATH.orderDetail + '/' + id);
    }

    // 评价订单
    comment = (id?: string) => {
        this.props.history!.push(ROUTE_PATH.serviceComment + '/' + id);
    }

    repay = (id: string) => {
        // TODO:失败付款后重新付款页面未完成
        this.props.history!.push(ROUTE_PATH.repayment + '/' + id);
    }

    chargeBack = (id: string) => {
        this.props.history!.push(ROUTE_PATH.chargeBack + '/' + id);
    }

    getOperation = (owData: any) => {
        if (owData.pay_state === '待支付') {
            return (
                <Row gutter={20}>
                    <WhiteSpace size='md' />
                    <Col style={{ textAlign: 'right' }}>
                        <Button style={{ marginRight: '1em' }}>取消订单</Button>
                        <Button type='primary' onClick={() => this.repay(owData.id)}>付款</Button>
                    </Col>
                </Row>
            );
        }

        if (owData.status === '服务中') {
            return (
                <Row gutter={20}>
                    <WhiteSpace size='md' />
                    <Col style={{ textAlign: 'right' }}>
                        <Button onClick={() => this.onClickContact(owData[serverArrKey])}>联系服务人员</Button>
                    </Col>
                </Row>
            );
        }

        if (owData.status === '未服务') {
            return (
                <Row gutter={20}>
                    <WhiteSpace size='md' />
                    <Col style={{ textAlign: 'right' }}>
                        {/* TODO：未根据长者或者服务人员来显示：长者--待派工  工作人员--开始执行 */}
                        <Button onClick={() => this.chargeBack(owData.id)}>申请退单</Button>
                        {/* <Button>派工</Button> */}
                    </Col>
                </Row>
            );
        }

        return (
            <Row gutter={20}>
                <WhiteSpace size='md' />
                <Col style={{ textAlign: 'right' }}>
                    <Button type='primary' onClick={this.comment.bind(this, owData.id)}>{owData['comment_info'] && owData['comment_info'].length > 0 ? '查看评价' : '评价'}</Button>
                </Col>
            </Row>
        );
    }

    render() {
        const { list, dataSource, will_service, service_ing, did_service } = this.state;
        setMainFormTitle('我的订单');
        // 获取item进行展示
        const renderRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <div>
                    <Card className='list-conten'>
                        <Row type='flex' justify='center' >
                            <WhiteSpace size='md' />
                            <Row gutter={20}>
                                <WhiteSpace size='md' />
                                <Col span={12}>{owData.orgnization_name[0]}</Col>
                                <Col span={12} style={{ textAlign: 'right' }}>{owData.status === '未服务' ? "待服务" : owData.status}</Col>
                            </Row>
                            {
                                owData.detail ? owData.detail.map((item: any, key: any) => {
                                    return (
                                        <Row key={key} onClick={this.onClickRow.bind(this, owData.id)}>
                                            <WhiteSpace size="lg" />
                                            <Col className='list-col' span={10}><img src={owData.product_img ? owData.product_img[0] : 'https://www.e-health100.com/api/attachment/servicetype/typePicture2_225?1516587849871'} style={{ height: '72pt', width: '100%' }} /></Col>
                                            <Col span={14} className='list-col'>
                                                <Row><strong>{item.product_name}</strong></Row>
                                                <Row>
                                                    {
                                                        item.service_option ? item.service_option.map((opt: any, opt_key: any) => {
                                                            return opt.name + ":" + opt.option_value ? opt.option_value : opt.default_value + ';';
                                                        }) : ''
                                                    }
                                                </Row>
                                                <Row>￥{owData['product_amount'][key]}</Row>
                                                <Row>x{item.count}</Row>
                                            </Col>
                                        </Row>
                                    );
                                }) : ''
                            }
                            <Row gutter={20}>
                                <Col style={{ textAlign: 'right' }}>共{owData.detail ? owData.detail.length : 0}件商品&nbsp; 合计：<strong>￥{owData.amount}</strong></Col>
                            </Row>
                            {this.getOperation(owData)}
                        </Row>
                    </Card>
                </div>
            );
        };
        return (
            <Spin spinning={this.state.loading}>
                <Row>
                    <Tabs
                        tabs={tabs}
                        initialPage={0}
                    >

                        <div className='tabs-content'>
                            {
                                list && list.length ?
                                    <ListView
                                        ref={el => this['lv'] = el}
                                        dataSource={dataSource.cloneWithRows(list)}
                                        renderRow={renderRow}
                                        initialListSize={10}
                                        pageSize={10}
                                        renderBodyComponent={() => <MyBody />}
                                        style={{ height: this.state.height }}
                                    />
                                    :
                                    <Row className='tabs-content' type='flex' justify='center'>
                                        暂无数据
                                </Row>

                            }
                        </div>
                        <div className='tabs-content'>
                            {
                                will_service && will_service.length ?
                                    <ListView
                                        ref={el => this['lv'] = el}
                                        dataSource={dataSource.cloneWithRows(will_service)}
                                        renderRow={renderRow}
                                        initialListSize={10}
                                        pageSize={10}
                                        renderBodyComponent={() => <MyBody />}
                                        style={{ height: this.state.height }}
                                    />
                                    :
                                    <Row className='tabs-content' type='flex' justify='center'>
                                        暂无数据
                                </Row>

                            }
                        </div>
                        <div className='tabs-content'>
                            {
                                service_ing && service_ing.length ?
                                    <ListView
                                        ref={el => this['lv'] = el}
                                        dataSource={dataSource.cloneWithRows(service_ing)}
                                        renderRow={renderRow}
                                        initialListSize={10}
                                        pageSize={10}
                                        renderBodyComponent={() => <MyBody />}
                                        style={{ height: this.state.height }}
                                    />
                                    :
                                    <Row className='tabs-content' type='flex' justify='center'>
                                        暂无数据
                                </Row>
                            }
                        </div>
                        <div className='tabs-content'>
                            {
                                did_service && did_service.length ?
                                    <ListView
                                        ref={el => this['lv'] = el}
                                        dataSource={dataSource.cloneWithRows(did_service)}
                                        renderRow={renderRow}
                                        initialListSize={10}
                                        pageSize={10}
                                        renderBodyComponent={() => <MyBody />}
                                        style={{ height: this.state.height }}
                                    />
                                    :
                                    <Row className='tabs-content' type='flex' justify='center'>
                                        暂无数据
                                </Row>
                            }
                        </div>
                    </Tabs>
                    <Modal
                        visible={this.state.open_link_server}
                        closable={false}
                        // okButtonProps={{ disabled: !this.state.is_agree }}
                        okText={"确定"}
                        title={"联系服务人员"}
                        // onOk={this.goPayment}
                        onCancel={() => this.setState({ open_link_server: false })}
                        cancelText={"关闭"}
                    >
                        <List
                            itemLayout="horizontal"
                            dataSource={this.state.server_link_info}
                            renderItem={item => {
                                return (
                                    <List.Item>
                                        <a href={"tel:" + item['personnel_info']['telephone']} onClick={() => this.setState({ open_link_server: false })}>{item['personnel_info']['name']}：{item['personnel_info']['telephone']}</a>
                                    </List.Item>
                                );
                            }}
                        />
                    </Modal>
                </Row>
            </Spin>
        );
    }
}

/**
 * 组件：我的订单表视图控件
 * 控制我的订单表视图控件
 */
@addon('ServiceListView', '我的订单表视图控件', '控制我的订单表视图控件')
@reactControl(MyOrderView, true)
export class MyOrderViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}